package com.sourceQ.common.core.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * @author: SourceQ
 * @create: 2024-03-29 11:15
 * @Description:中文转拼音工具类
 */
public class SpellUtils {
    /**
     * 中文转拼音
     * @param chinese
     * @return
     * @throws BadHanyuPinyinOutputFormatCombination
     */
    public static String getEName(String chinese) throws BadHanyuPinyinOutputFormatCombination {
        HanyuPinyinOutputFormat pyFormat = new HanyuPinyinOutputFormat();
        pyFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        pyFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        pyFormat.setVCharType(HanyuPinyinVCharType.WITH_V);

        return PinyinHelper.toHanyuPinyinString(chinese, pyFormat, "");
    }

    /**
     * 中文转拼音缩写
     * @param chinese
     * @return
     */
    public static String getENameAbbr(String chinese){
        StringBuilder sb = null;
        try {
            HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
            format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
            format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
            sb = new StringBuilder();
            char[] chars = chinese.toCharArray();
            for (char c : chars) {
                String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, format);
                if (pinyinArray != null && pinyinArray.length > 0) {
                    sb.append(pinyinArray[0].charAt(0));
                } else {
                    sb.append(c);//不是汉字则直接拼接
                }
            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {


        }
        return sb.toString();
    }

    public static void main(String[] args) throws BadHanyuPinyinOutputFormatCombination {
        System.out.println(getEName("你好"));
        System.out.println(getENameAbbr("中国科技"));
    }
}
